<template>
  <div style="position: relative;min-height: 80vh;">
    <!-- 头部 -->
    <myDivider name="新建巡查任务"></myDivider>
    <el-page-header @back="$router.go(-1)">
    </el-page-header>



    <!-- 表单 -->
    <el-form ref="ruleForm" class="fromStyle" :rules="rules" :model="formData" label-width="150px">
      <el-form-item label="任务名称：" prop="name">
        <el-input v-model="formData.name" placeholder="任务名称"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="巡查人：" prop="people">
            <el-select v-model="formData.people" placeholder="请选择" @change="peopleChange">
              <el-option label="一般" value="1"></el-option>
              <el-option label="紧急" value="2"></el-option>
              <el-option label="特急" value="3"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式：">
            <el-input v-model="formData.phone" disabled placeholder="联系方式"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="巡查码：" prop="" required>
        <div>
          <el-button type="primary" @click="openPop">选择巡查码</el-button>
          <div class="xcmBox" v-if="formData.checkCardArr.length > 0">
            <div class="xcmEl" v-for="item, i in formData.checkCardArr" :key="i">
              <div class="F1">
                <span>巡查类别</span>
                <span>{{ item.name }}</span>
              </div>
              <div class="F2">
                <span>所属小区</span>
                <el-tooltip class="item" effect="dark" content="保洁巡查" placement="top-start">
                  <span>保洁巡查</span>
                </el-tooltip>
              </div>
              <div class="F3">
                <span>名称</span>
                <span>保洁巡查</span>
              </div>
              <div class="F4">
                <span>位置</span>
                <el-tooltip class="item" effect="dark" content="保洁巡查" placement="top-start">
                  <span>保洁巡查</span>
                </el-tooltip>
                <span @click="seeMap({ longitude: 115.913174, latitude: 39.970082 })">查看地图</span>
              </div>
              <div class="F5">
                <span class="d1">位置参考图</span>
                <el-image style="width: 50px; height: 50px"
                  src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
                  :preview-src-list="['https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg']">
                </el-image>
                <span class="d2">二维码</span>
                <el-image style="width: 50px; height: 50px"
                  src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
                  :preview-src-list="['https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg']">
                </el-image>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item label="巡查时间：" prop="radio">
        <template>
          <el-radio-group v-model="formData.radio" @input="radioChange">
            <el-radio label="daily">每日</el-radio>
            <el-radio label="weekly">每周</el-radio>
            <el-radio label="monthly">每月</el-radio>
            <el-radio label="timeSlot">
              <el-date-picker value-format="yyyy-MM-dd" @change="dayChange" v-model="formData.day" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-radio>
          </el-radio-group>

          <!-- 每周/每月的选择项 -->
          <div class="checkBoxStyle" v-if="formData.radio == 'weekly' || formData.radio == 'monthly'">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
              @change="checkChange('全选', $event)">全选</el-checkbox>
            <div style="margin: 15px 0;"></div>
            <el-checkbox-group v-model="formData.checkTimeArr" @change="checkChange('单选', $event)">
              <el-checkbox v-for="item, i in checkTimeData" :key="i" :label="item.id">{{ item.name }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </template>
      </el-form-item>

      <el-form-item label="提醒时间：">
        <span>将在巡查当天</span>
        <el-time-picker :editable="false" style="width: 120px;" value-format="HH:mm" format="HH:mm"
          v-model="formData.time" :picker-options="{
            selectableRange: '00:00:00 - 23:59:59',
          }" placeholder="任意时间">
        </el-time-picker>
        <span>给巡查人发送提醒消息</span>
      </el-form-item>

      <el-form-item label="任务类型：">
        连续性任务
      </el-form-item>
    </el-form>

    <div class="btn">
      <el-button style="width: 100px;" @click="cancel">取消</el-button>
      <el-button style="width: 100px;" type="primary" @click="okk">确认</el-button>
    </div>

    <!-- 选择巡查码弹窗 -->
    <el-dialog title="选择巡查码" :visible.sync="popShow" width="1000px" class="popPatrolBox">
      <div class="popPatrolTop">
        <el-input style="width: 200px;" v-model="keyNameType" placeholder="巡查码名称/类别"></el-input>
        <el-select style="width: 200px;" @change="getPopList" clearable v-model="keyResidentialId" placeholder="选择小区">
          <el-option v-for="item, i in keyResidentialData" :key="i" :label="item.name" :value="item.residentialId">
          </el-option>
        </el-select>
        <el-button type="primary" style=" margin-left: 15px" @click="getPopList">查询</el-button>
        <el-button style="margin-left: 15px" @click="reset">重置</el-button>
      </div>
      <div class="popPatrolMain">
        <el-checkbox :indeterminate="popIsIndeterminate" v-model="popCheckAll"
          @change="popCheckAllClick">全选</el-checkbox>
        <div class="popPatrolListbox">
          <div class="popPatrolListboxEl" :class="popPatrolclassEvent(item)" v-for="item, i in popList" :key="i"
            @click="popPatrolListElClick(item)">
            <div class="F1">
              <span>巡查类别</span>
              <span>保洁巡查</span>
            </div>
            <div class="F2">
              <span>所属小区</span>
              <el-tooltip class="item" effect="dark" content="保洁巡查" placement="top-start">
                <span>保洁巡查</span>
              </el-tooltip>
            </div>
            <div class="F3">
              <span>名称</span>
              <span>保洁巡查</span>
            </div>
            <div class="F4">
              <span>位置</span>
              <el-tooltip class="item" effect="dark" content="保洁巡查" placement="top-start">
                <span>保洁巡查</span>
              </el-tooltip>
              <span @click="seeMap({ longitude: 115.913174, latitude: 39.970082 })">查看地图</span>
            </div>
            <div class="F5">
              <span class="d1">位置参考图</span>
              <el-image style="width: 50px; height: 50px"
                src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
                :preview-src-list="['https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg']">
              </el-image>
              <span class="d2">二维码</span>
              <el-image style="width: 50px; height: 50px"
                src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"
                :preview-src-list="['https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg']">
              </el-image>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="popShow = false">取 消</el-button>
        <el-button type="primary" @click="popokk">确 定</el-button>
      </span>
    </el-dialog>



    <!-- 地图弹窗 -->
    <el-dialog title="位置信息" :visible.sync="mapShow" width="80%">
      <div class="mapStyle">
        <span style="display: block;margin-bottom: 15px;font-size: 20px;font-weight: 600">{{ '选择的位置：' + positionName
          }}</span>

        <div id="container"></div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
window._AMapSecurityConfig = {
  securityJsCode: "74a9bc741a93c4984284167952f22f4a",//安全密钥
};
export default {

  data() {
    var validateName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入任务名称'));
      } else {
        if (value == '123') {
          callback(new Error('任务名称已存在'));
        } else {
          callback();
        }

      }
    }
    return {
      scene: '',
      rules: {
        name: [
          { validator: validateName, trigger: 'blur' }
        ],
        people: [
          { required: true, message: '请选择巡查人', trigger: 'change' }
        ],
        radio: [
          { required: true, message: '请选择巡查时间', trigger: 'change' }
        ],

      },
      formData: {
        checkTimeArr: [], //选中的日期
        checkCardArr: [],// 选中的巡查码卡片 
      },
      checkTimeData: [],
      checkAll: false, //全选状态
      isIndeterminate: false, //半选状态


      // 地图相关
      positionName: '',
      map: null,
      marker: null,
      geocoder: null,//编码
      AMap: null,
      mapShow: false,
      // 地图相关 ===================


      popShow: false,
      keyNameType: '', //名称筛选
      keyResidentialId: '',//小区筛选
      keyResidentialData: [],
      popCheckAll: false,
      popIsIndeterminate: false,
      popList: [
        { name: '1', id: 1 },
        { name: '2', id: 2 },
        { name: '3', id: 3 },
        { name: '4', id: 4 },
      ]
    }
  },
  created() {

  },
  async activated() {

    this.scene = this.$route.query.scene
    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.getkeyResidentialData() //获取筛选项的小区列表

    // 清空内容
    if (this.scene == 'add') {
      this.$set(this.formData, 'name', '')
      this.$set(this.formData, 'people', '')
      this.$set(this.formData, 'phone', '')
      this.$set(this.formData, 'radio', '')
      this.$set(this.formData, 'day', '')
      this.$set(this.formData, 'time', '')
      this.formData.checkTimeArr = []
      this.formData.checkCardArr = []
      this.checkAll = false
      this.isIndeterminate = false
      this.popCheckAll = false
      this.popIsIndeterminate = false
    } else {

    }



    this.$nextTick(() => {
      this.$refs['ruleForm'].clearValidate()
    })


  },
  methods: {
    popokk() { //选择巡查码弹窗 确认事件
      console.log(this.formData.checkCardArr, 'qwcqcqwc');
      this.popShow = false
    },

    openPop() { //选择巡查码按钮
      this.popShow = true
      this.reset()
      this.$nextTick(() => {
      })
    },
    reset() {
      this.keyNameType = ''
      this.keyResidentialId = ''
      this.getPopList()
    },
    getPopList() {
      // 如果选中的  高亮
    },
    popCheckAllClick(e) { //选择巡查码的 全选按钮事件

      if (e) {
        this.formData.checkCardArr = JSON.parse(JSON.stringify(this.popList))
      } else {
        this.formData.checkCardArr = []
      }
      this.popIsIndeterminate = false;
    },
    popPatrolclassEvent(item) {
      let have = false
      this.formData.checkCardArr.forEach((el, i) => {
        if (el.id == item.id) {
          have = true
        }
      })
      if (!have) {
        return ''
      } else {
        return 'active'
      }
    },
    popPatrolListElClick(item) { //巡查码点击事件，选中或取消
      let have = false
      this.formData.checkCardArr.forEach((el, i) => {
        if (el.id == item.id) {
          this.formData.checkCardArr.splice(i, 1)
          have = true
        }
      })
      if (!have) {
        this.formData.checkCardArr.push(item)
      }

      // 设置选择巡查码的复选框 选中/未选择状态
      this.popCheckAll = this.formData.checkCardArr.length === this.popList.length
      // 设置选择巡查码的复选框半选状态
      this.popIsIndeterminate = this.formData.checkCardArr.length > 0 && this.formData.checkCardArr.length < this.popList.length
    },
    async getkeyResidentialData() {
      let res = await this.$api.patrol.myPatrolGetCommunityList('')
      if (res.code == 200) {
        this.keyResidentialData = res.data
        console.log(this.keyResidentialData, 'this.keyResidentialData');
      } else {
        this.$message.error(res.message)
      }
    },
    peopleChange() {
      this.formData.phone = '6666666666'
    },
    checkChange(type, e) {
      switch (type) {
        case '全选': //此时e为 true/false
          if (e) { // 全部选中
            this.formData.checkTimeArr = []
            this.checkTimeData.forEach(el => {
              this.formData.checkTimeArr.push(el.id)
            })
          } else { //全部取消
            this.formData.checkTimeArr = []
          }
          this.isIndeterminate = false;
          break
        case '单选': // 此时e为单选选中的数组
          this.checkAll = e.length === this.checkTimeData.length;
          this.isIndeterminate = e.length > 0 && e.length < this.checkTimeData.length;
          break
      }
      console.log(this.formData.checkTimeArr, 'abcd');
    },
    radioChange() {

      switch (this.formData.radio) {
        case 'daily':
          this.$set(this.formData, 'day', '')
          this.checkAll = false
          this.isIndeterminate = false
          this.$set(this.formData, 'checkTimeArr', [])
          break
        case 'weekly':
          this.$set(this.formData, 'day', '')
          this.checkAll = false
          this.isIndeterminate = false
          this.$set(this.formData, 'checkTimeArr', [])
          // 获取周一到周日的数据
          this.checkTimeData = [
            { name: '周一', id: 1 },
            { name: '周二', id: 2 },
          ]
          break
        case 'monthly':
          this.$set(this.formData, 'day', '')
          this.checkAll = false
          this.isIndeterminate = false
          this.$set(this.formData, 'checkTimeArr', [])
          // 获取1号到月底的数据
          this.checkTimeData = [
            { name: '1号', id: 1 },
            { name: '2号', id: 2 },
          ]
          break
        case 'timeSlot':
          this.checkAll = false
          this.isIndeterminate = false
          this.$set(this.formData, 'checkTimeArr', [])
          break
      }

    },
    dayChange(e) {
      console.log(e,'qdqwdqw');
      this.$set(this.formData, 'radio', 'timeSlot')
    },
    okk() {
      if ((this.formData.radio == 'weekly' || this.formData.radio == 'monthly') && !this.checkAll && !this.isIndeterminate) {
        this.$message.error('请选择巡查时间')
        return
      }
      if (this.formData.checkCardArr.length == 0) {
        this.$message.error('请选择巡查码')
        return
      }
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          console.log(this.formData, '恭喜过关');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    cancel() {
      this.$confirm('返回后不保存内容，确定返回吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.$router.go(-1)
      }).catch(() => {

      });
    },

    seeMap(item) {
      this.mapShow = true
      console.log(item)
      if (!item.longitude) {
        this.$message.error('缺少定位')
        return
      }
      this.positionName = item.longitude
      this.$nextTick(() => {
        AMapLoader.load({
          key: "b59ffa4664995330f554d4aedc02b03c", // 申请好的Web端开发者Key，首次调用 load 时必填
          version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ['AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        })
          .then((AMap) => {
            this.AMap = AMap

            let mylatlot = [item.longitude, item.latitude]
            console.log(mylatlot, 'mylatlot');
            this.map = new AMap.Map("container", {
              // viewMode: "3D", // 是否为3D地图模式
              zoom: 15, // 初始化地图级别
              center: mylatlot, // 初始化地图中心点位置
            });
            this.map.on('complete', () => { //地图加载完毕函数
              this.marker = new this.AMap.Marker({ //创建点标点
                position: mylatlot,
              });
              this.map.add(this.marker);    //添加点标点
            });
          })
          .catch((e) => {
            console.log(e);
          });


      })
    },
  },


}
</script>

<style lang="less" scoped>
.popPatrolBox {

  .popPatrolMain {
    margin-top: 20px;

    .popPatrolListbox {
      margin-top: 10px;
      height: 420px;
      overflow-y: scroll;
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      // justify-content: space-between;

      &::-webkit-scrollbar {
        width: 2px !important;

        &-thumb {
          background-color: #ebebeb;
        }
      }

      .popPatrolListboxEl {
        cursor: pointer;
        margin: 10px 8px 0;
        background-color: white;
        border: 1px solid rgb(203, 203, 203);
        box-sizing: border-box;
        width: 300px;
        height: 200px;
        // margin: 5px 0;
        padding: 0 20px;
        box-sizing: border-box;

        &.active {
          background-color: #e7f5ff;
          border: 1px solid #409eff;
        }

        .F1,
        .F2,
        .F3 {
          width: 100%;
          display: flex;
          font-size: 12px;
          line-height: 35px !important;

          span {
            &:nth-child(1) {
              width: 80px;
            }

            &:nth-child(2) {
              flex: 1;
              font-weight: bold;
              overflow: hidden;
              -webkit-line-clamp: 1;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-box-orient: vertical;
            }
          }
        }

        .F4 {
          width: 100%;
          display: flex;
          font-size: 12px;
          line-height: 35px !important;

          span {
            &:nth-child(1) {
              width: 80px;
            }

            &:nth-child(2) {
              flex: 1;
              margin-right: 5px;
              overflow: hidden;
              -webkit-line-clamp: 1;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-box-orient: vertical;
            }

            &:nth-child(3) {
              color: #22a5f1;
              cursor: pointer;
            }
          }
        }

        .F5 {
          display: flex;

          .d1 {
            width: 80px;
          }

          .d2 {
            width: 80px;
            text-align: center;
          }
        }
      }

    }
  }
}

.mapStyle {
  height: 65vh;
  width: 100%;

  #container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 90%;
  }
}

.xcmBox {
  margin-top: 10px;
  height: 210px;
  overflow-y: scroll;
  width: 610px;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  &::-webkit-scrollbar {
    width: 2px !important;

    &-thumb {
      background-color: #ebebeb;
    }
  }

  .xcmEl {
    background-color: #e7f5ff;
    border: 1px solid #409eff;
    box-sizing: border-box;
    width: 300px;
    height: 200px;
    margin: 5px 0;
    padding: 0 20px;
    box-sizing: border-box;

    .F1,
    .F2,
    .F3 {
      width: 100%;
      display: flex;
      font-size: 12px;
      line-height: 35px !important;

      span {
        &:nth-child(1) {
          width: 80px;
        }

        &:nth-child(2) {
          flex: 1;
          font-weight: bold;
          overflow: hidden;
          -webkit-line-clamp: 1;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
        }
      }
    }

    .F4 {
      width: 100%;
      display: flex;
      font-size: 12px;
      line-height: 35px !important;

      span {
        &:nth-child(1) {
          width: 80px;
        }

        &:nth-child(2) {
          flex: 1;
          margin-right: 5px;
          overflow: hidden;
          -webkit-line-clamp: 1;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
        }

        &:nth-child(3) {
          color: #22a5f1;
          cursor: pointer;
        }
      }
    }

    .F5 {
      display: flex;

      .d1 {
        width: 80px;
      }

      .d2 {
        width: 80px;
        text-align: center;
      }
    }
  }
}

.checkBoxStyle {

  padding: 10px;
  background-color: rgb(236 245 255);
  border-radius: 15px;
  box-sizing: border-box;
  margin-top: 10px;
}

.fromStyle {
  margin-top: 50px;
  width: 775px;
}



// 添加取消按钮
.btn {
  // margin-top: 50px;
  background-color: white;
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 4px 1px #e1e1e1;
}
</style>